package cn.acheng1314.utils
import java.security.MessageDigest
import java.security.SecureRandom
import kotlin.experimental.and


open class HashKit {
    companion object {
        private val random = SecureRandom()
        private val HEX_DIGITS = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
        fun md5(srcStr: String): String {
            return hash("MD5", srcStr)
        }

        fun sha1(srcStr: String): String {
            return hash("SHA-1", srcStr)
        }

        fun sha256(srcStr: String): String {
            return hash("SHA-256", srcStr)
        }

        fun sha384(srcStr: String): String {
            return hash("SHA-384", srcStr)
        }

        fun sha512(srcStr: String): String {
            return hash("SHA-512", srcStr)
        }

        fun hash(algorithm: String?, srcStr: String): String {
            return try {
                val md = MessageDigest.getInstance(algorithm)
                val bytes = md.digest(srcStr.toByteArray(charset("utf-8")))
                toHex(bytes)
            } catch (e: Exception) {
                throw RuntimeException(e)
            }
        }

        private fun toHex(bytes: ByteArray): String {
            val ret = StringBuilder(bytes.size * 2)
            for (i in bytes.indices) {
                ret.append(HEX_DIGITS[bytes[i].toInt() shr 4 and 0x0f])
                ret.append(HEX_DIGITS[bytes[i].toInt() and 0x0f])
            }
            return ret.toString()
        }

        /**
         * md5 128bit 16bytes
         * sha1 160bit 20bytes
         * sha256 256bit 32bytes
         * sha384 384bit 48bites
         * sha512 512bit 64bites
         */
        fun generateSalt(numberOfBytes: Int): String {
            val salt = ByteArray(numberOfBytes)
            random.nextBytes(salt)
            return toHex(salt)
        }
    }
}
